package com.huiminpay.merchant.service.impl;

import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.merchant.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: yz
 * @Date: 2024/7/18 19:08
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Autowired
    RestTemplate restTemplate;

    @Value("${sms.url}") // - url：验证码服务地址
    private String smsUrl;

    @Value("${sms.effectiveTime}") //- eﬀectiveTime：验证码过期时间
    private String effectiveTime;
    /**
     * 发送手机验证码
     *
     * @param phone 手机号
     * @return 验证码对应的key
     */
    @Override
    public String sendSms(String phone) throws BusinessException {

        String url = smsUrl+"/generate?name=sms&effectiveTime="+effectiveTime;

//        System.out.println(10/0); //测试未知异常


        //组装头部信息
        HashMap<String, String> map = new HashMap<>();
        map.put("mobile", phone);
        HttpHeaders httpHeaders = new HttpHeaders();
        //httpHeaders.set("Content-Type", "application/json");
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<HashMap<String, String>> httpEntity = new HttpEntity<>(map, httpHeaders);

        Map body = null;
        try {
            //                          请求路径  请求方式  携带的数据(数据 请求头) 响应的数据类型
            ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class);
            body = response.getBody();
            log.info("响应结果:{}", body);
        } catch (RestClientException e) {
            log.info("获取验证码失败");
//            throw new RuntimeException(e);
            throw new BusinessException(CommonErrorCode.E_100107);
        }

        if (body!=null && body.get("result")!=null){

            Map<String,String> result = (Map<String, String>) body.get("result");
            String key = result.get("key");
            log.info("验证key:{}",key);
            return key;
        }else{
            log.info("获取验证码失败");
//            throw new RuntimeException("获取验证码失败");
            throw new BusinessException(CommonErrorCode.E_100107);

        }
    }


    /**
     * 校验验证码
     *
     * @param verifiykey  验证码key
     * @param verifiyCode 验证码code
     */
    @Override
    public void checkSmsCode(String verifiykey, String verifiyCode) throws BusinessException {
        //POST
        String url=smsUrl+"/verify?name=sms&verificationCode="+ verifiyCode +"&verificationKey="+verifiykey;

        Map body = null;
        try {
            ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, HttpEntity.EMPTY, Map.class);
            body = response.getBody();
            log.info("响应结果:{}",body);
        } catch (RestClientException e) {
            log.info("验证码错误!!");
//            throw new RuntimeException(e);
            throw new BusinessException(CommonErrorCode.E_100102);
        }

        if (body==null || !(Boolean) body.get("result")){
            log.info("验证码错误!!");
//            throw new RuntimeException("验证码错误!!");
            throw new BusinessException(CommonErrorCode.E_100102);

        }

    }
}
